package com.imooc.dao.impl;

import com.imooc.dao.StudentDAO;
import com.imooc.domain.Student;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zghgchao 2017/12/29 15:52
 * StudentDAO访问接口实现类：通过Spring jdbc的方式操作
 */
public class StudentDAOSpringJdbcImpl implements StudentDAO{

    private JdbcTemplate jdbcTemplate;

    public List<Student> query() {
        final List<Student> students = new ArrayList<Student>();
        String sql = "select id,name,age from student";

        jdbcTemplate.query(sql, new RowCallbackHandler() {
            public void processRow(ResultSet rs) throws SQLException {
                Student student = new Student(rs.getInt("id"), rs.getString("name"), rs.getInt("age"));
                students.add(student);
            }
        });
        return students;
    }

    public void save(Student student) {
        String sql = "INSERT INTO student (name, age) VALUES (?, ?)";
        jdbcTemplate.update(sql,new Object[]{student.getName(),student.getAge()});
    }

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}
